package fu.capstone.hanoicityguide.presentation.fragment.nearby;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SearchView;
import fu.capstone.hanoicityguide.R;
import fu.capstone.hanoicityguide.business.bo.nearbyplace.NearbyPlaceBO;
import fu.capstone.hanoicityguide.business.bo.nearbyplace.NearbyPlaceBOImp;
import fu.capstone.hanoicityguide.business.model.Category;
import fu.capstone.hanoicityguide.business.model.Place;
import fu.capstone.hanoicityguide.common.utility.InternetSetting;
import fu.capstone.hanoicityguide.common.utility.LocationSetting;
import fu.capstone.hanoicityguide.presentation.adapter.ListPlaceAdapter;
import fu.capstone.hanoicityguide.presentation.fragment.attraction.DetailAttractionFragment;
import fu.capstone.hanoicityguide.presentation.fragment.home.HomeFragment;
import fu.capstone.hanoicityguide.presentation.fragment.hotel.DetailHotelFragment;
import fu.capstone.hanoicityguide.presentation.fragment.nightlife.DetailNightLifeFragment;
import fu.capstone.hanoicityguide.presentation.fragment.restaurant.DetailRestaurantFragment;

@SuppressLint("ValidFragment")
public class ListNearbyPlaceFragment extends Fragment implements
		SearchView.OnQueryTextListener, SearchView.OnCloseListener {

	private NearbyPlaceBO nearbyBO;
	private ArrayList<Place> arrNearby;
	private String[] arrType;
	private ArrayList<Category> arrCategory = null;
	private ArrayList<String> filter;
	private String sorter;
	private ListPlaceAdapter nearbyAdapter = null;
	private ListView listNearby = null;
	private SearchView searchView;
	private String keyword;
	private boolean[] itemChecked;
	private boolean[] oldChecked;
	private DrawerLayout drawer;
	private LocationListener locationListener;
	private LocationSetting locationSetting;
	private InternetSetting internetSetting;
	private Location lastKnownLoc;

	public ListNearbyPlaceFragment(DrawerLayout drawer) {
		this.drawer = drawer;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// init
		View listNearbyFragment = inflater.inflate(
				R.layout.fragment_list_nearbyplace, container, false);
		try {
			setHasOptionsMenu(true);
			nearbyBO = new NearbyPlaceBOImp(container.getContext());
			listNearby = (ListView) listNearbyFragment
					.findViewById(R.id.listNearby);

			arrNearby = new ArrayList<Place>();

			// set filter and sorter
			filter = new ArrayList<String>();
			setKeyword("");
			// setFilter("All");
			setSorter(getResources().getStringArray(R.array.sorter_items)[0]);

			// get category
			arrCategory = new ArrayList<Category>();
			arrCategory = nearbyBO.getListCategory("");
			arrType = new String[5];
			arrType[0] = "All";
			if (arrCategory.size() > 0) {
				// get all category to filter
				for (int i = 0; i < arrCategory.size(); i++) {
					arrType[i + 1] = arrCategory.get(i).getCategoryName();
				}
			}

			filter.add("All");
			for (int i = 0; i < arrCategory.size(); i++) {
				filter.add(arrCategory.get(i).getCategoryName());
			}

			// init checked item
			itemChecked = new boolean[arrType.length];
			for (int i = 0; i < itemChecked.length; i++) {
				itemChecked[i] = true;
			}

			// get all list Nearby

			// getting GPS
			locationSetting = new LocationSetting(getActivity());
			internetSetting = new InternetSetting(getActivity());
			LocationManager locManager = (LocationManager) getActivity()
					.getSystemService(Context.LOCATION_SERVICE);
			locationListener = new MyLocationListener();
			locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1,
					1, locationListener);

			if (!locationSetting.getGPSSetting(getActivity())) {
				locationSetting.showSettingsAlert();
			} else {
				String provider;
				Criteria criteria = new Criteria();
				provider = locManager.getBestProvider(criteria, false);
				lastKnownLoc = null;

				lastKnownLoc = locManager
						.getLastKnownLocation(LocationManager.GPS_PROVIDER);

				arrNearby = nearbyBO.listNearbyPlace(
						lastKnownLoc.getLatitude(),
						lastKnownLoc.getLongitude(), 1000, getKeyword(),
						getFilter(), getSorter());
			}
			// Log.v("Array Count :", arrNearby.size() + "");
			nearbyAdapter = new ListPlaceAdapter(getActivity(),
					R.layout.adapter_list_place, arrNearby);

			// set listview adapter and create event for items click
			listNearby.setAdapter(nearbyAdapter);

			listNearby.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// call Detail Fragment of Place
					Fragment browsePlace = null;
					switch (arrNearby.get(position).getCategory()) {
					case "Attraction":
						browsePlace = new DetailAttractionFragment(arrNearby
								.get(position).getId());
						break;
					case "Hotel":
						browsePlace = new DetailHotelFragment(arrNearby.get(
								position).getId());
						break;
					case "Restaurant":
						browsePlace = new DetailRestaurantFragment(arrNearby
								.get(position).getId());
						break;
					case "Nightlife":
						browsePlace = new DetailNightLifeFragment(arrNearby
								.get(position).getId());
						break;
					default:
						break;
					}

					if (browsePlace != null) {
						FragmentManager fragmentManager = getFragmentManager();
						FragmentTransaction fTransaction = fragmentManager
								.beginTransaction();
						fTransaction.addToBackStack(null);
						fTransaction.replace(R.id.frame_container, browsePlace)
								.commit();
						getActivity().setTitle(
								arrNearby.get(position).getName());
					}
				}
			});
		} catch (Exception e) {
			Log.e("ListNearbyPlaceFragment : ", e.toString());
		}

		return listNearbyFragment;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

		// create option menu in actionbar
		inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.list_nearbyplace_menu, menu);

		// Associate searchable configuration with the SearchView
		searchView = (SearchView) menu.findItem(R.id.action_search_nearby)
				.getActionView();
		setupSearchView();
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// create event for items of option menu in actionbar
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		AlertDialog dialog;
		Fragment fragment = new Fragment();
		internetSetting = new InternetSetting(getActivity());
		switch (item.getItemId()) {

		case R.id.action_showmap: {

			if (internetSetting.getConnectivityStatus(getActivity())) {
				fragment = new NearbyOnlineMapFragment(getKeyword(),
						getFilter(), getSorter());
				if (fragment != null) {
					FragmentManager fragmentManager = getFragmentManager();
					FragmentTransaction fTransaction = fragmentManager
							.beginTransaction();
					fTransaction.addToBackStack(null);
					fTransaction.replace(R.id.frame_container, fragment)
							.commit();
					getActivity().setTitle("View on map");
				}
			}
			if (!internetSetting.getConnectivityStatus(getActivity())
					&& HomeFragment.isPurchased) {
				fragment = new NearbyOfflineMapFragment(getKeyword(),
						getFilter(), getSorter());
				if (fragment != null) {
					FragmentManager fragmentManager = getFragmentManager();
					FragmentTransaction fTransaction = fragmentManager
							.beginTransaction();
					fTransaction.addToBackStack(null);
					fTransaction.replace(R.id.frame_container, fragment)
							.commit();
					getActivity().setTitle("View on map");
				}
			}

			if (!internetSetting.getConnectivityStatus(getActivity())
					&& !HomeFragment.isPurchased) {
				internetSetting.showSettingsAlert();
			}
		}
			break;
		// show filter dialog
		case R.id.action_filter_nearby:

			builder.setTitle("Filter");
			oldChecked = new boolean[itemChecked.length];
			for (int i = 0; i < oldChecked.length; i++) {
				oldChecked[i] = itemChecked[i];
			}
			// set event for check item
			builder.setMultiChoiceItems(arrType, itemChecked,
					new DialogInterface.OnMultiChoiceClickListener() {

						@Override
						public void onClick(DialogInterface dialog,
								int indexSelected, boolean isChecked) {
							AlertDialog alert = (AlertDialog) dialog;
							ListView list = alert.getListView();
							// check item
							if (isChecked) {
								// checked all
								if (indexSelected == 0) {
									for (int i = 1; i < arrType.length; i++) {
										list.setItemChecked(i, true);
										itemChecked[i] = true;
									}
								}
								// checked 1 item
								else {
									boolean checkAll = false;
									itemChecked[indexSelected] = true;
									// check all item
									for (int i = 1; i < itemChecked.length; i++) {
										if (itemChecked[i] == false) {
											checkAll = false;
											break;
										} else {
											checkAll = true;
										}
									}
									if (checkAll) {
										list.setItemChecked(0, true);
										itemChecked[0] = true;
									}
								}

							} else {
								// uncheck item
								if (indexSelected == 0) {
									for (int i = 1; i < arrType.length; i++) {
										list.setItemChecked(i, false);
										itemChecked[i] = false;
									}
								} else {
									list.setItemChecked(0, false);
									itemChecked[0] = false;
									itemChecked[indexSelected] = false;
								}
							}
						}
					});

			// Set the action buttons
			builder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							// set filter
							filter = new ArrayList<String>();
							for (int i = 1; i < itemChecked.length; i++) {
								if (itemChecked[i]) {
									filter.add(arrType[i]);
								}
							}

							// validating keyword , sorter , filter and
							// lastKnownLocation
							if (getKeyword() != null && getFilter() != null
									&& getSorter() != null
									&& lastKnownLoc != null
									&& arrNearby != null) {
								// get list nearby place from db
								arrNearby = nearbyBO.listNearbyPlace(
										lastKnownLoc.getLatitude(),
										lastKnownLoc.getLongitude(), 1000,
										getKeyword(), getFilter(), getSorter());

								nearbyAdapter.setArr(arrNearby);
								nearbyAdapter.notifyDataSetChanged();
							} else {
							}
						}
					});
			builder.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							// Your code when user clicked on Cancel
							for (int i = 0; i < oldChecked.length; i++) {
								itemChecked[i] = oldChecked[i];
							}
						}
					});

			dialog = builder.create();
			dialog.setCancelable(false);
			dialog.show();
			break;
		case R.id.action_sort_nearby:
			// String[] arrSorter = new String[4];
			builder.setTitle("Sort");
			builder.setItems(getResources()
					.getStringArray(R.array.sorter_items),
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int item) {
							// sort by sorter
							setSorter(getResources().getStringArray(
									R.array.sorter_items)[item]);
							if (getKeyword() != null && getFilter() != null
									&& getSorter() != null
									&& lastKnownLoc != null
									&& arrNearby != null) {
								// get list nearby place from db
								arrNearby = nearbyBO.listNearbyPlace(
										lastKnownLoc.getLatitude(),
										lastKnownLoc.getLongitude(), 1000,
										getKeyword(), getFilter(), getSorter());
								// reset array attraction in adapter
								nearbyAdapter.setArr(arrNearby);
								nearbyAdapter.notifyDataSetChanged();
							} else {
							}
						}
					});

			dialog = builder.create();
			dialog.show();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onResume() {
		// on resume change the title of actionbar to nightlife
		super.onResume();
		getActivity().getActionBar().setTitle("Nearby Places");
	}

	public ArrayList<String> getFilter() {
		return this.filter;
	}

	public void setFilter(ArrayList<String> filter) {
		this.filter = filter;
	}

	public String getSorter() {
		return this.sorter;
	}

	public void setSorter(String sorter) {
		this.sorter = sorter;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public String getKeyword() {
		return this.keyword;
	}

	private void setupSearchView() {

		searchView.setIconifiedByDefault(false);
		searchView.setQueryHint("Nearby Place Name");

		searchView
				.setOnQueryTextFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						// TODO Auto-generated method stub
						if (hasFocus) {
							drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
						} else {
							onClose();
						}
					}
				});

		searchView.setOnQueryTextListener(this);
		searchView.setOnCloseListener(this);
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		setKeyword(query);
		if (getKeyword() != null && getFilter() != null && getSorter() != null
				&& lastKnownLoc != null && arrNearby != null) {
			// get list nearby place from db
			arrNearby = nearbyBO.listNearbyPlace(lastKnownLoc.getLatitude(),
					lastKnownLoc.getLongitude(), 1000, getKeyword(),
					getFilter(), getSorter());
			nearbyAdapter.setArr(arrNearby);
			nearbyAdapter.notifyDataSetChanged();
			return true;
		} else {
			return false;
		}
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		// event occur when query text change
		setKeyword(newText);
		try {
			if (getKeyword() != null && getFilter() != null
					&& getSorter() != null && lastKnownLoc != null
					&& arrNearby != null) {
				// get list nearby place from db
				arrNearby = nearbyBO.listNearbyPlace(
						lastKnownLoc.getLatitude(),
						lastKnownLoc.getLongitude(), 1000, getKeyword(),
						getFilter(), getSorter());
				nearbyAdapter.setArr(arrNearby);
				nearbyAdapter.notifyDataSetChanged();
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			return false;
		}

	}

	@Override
	public boolean onClose() {
		// event occur when SearchView closed
		searchView.setQuery("", true);
		setKeyword("");
		if (getKeyword() != null && getFilter() != null && getSorter() != null
				&& lastKnownLoc != null && arrNearby != null) {
			// get list nearby place from db
			arrNearby = nearbyBO.listNearbyPlace(lastKnownLoc.getLatitude(),
					lastKnownLoc.getLongitude(), 1000, getKeyword(),
					getFilter(), getSorter());
			nearbyAdapter.setArr(arrNearby);
			nearbyAdapter.notifyDataSetChanged();

			return true;
		} else {
			return false;
		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		searchView = null;
		super.onDestroy();
		Log.v("List nearby on destroy", "destroyed");
		LocationManager locManager = (LocationManager) getActivity()
				.getSystemService(Context.LOCATION_SERVICE);
		locManager.removeUpdates(locationListener);
		locManager = null;
	}

	public class MyLocationListener implements LocationListener {
		public void onLocationChanged(Location location) {
			// Location pointLocation = retrievelocation();
			// float distance = location.distanceTo(pointLocation);
			try {
				String provider;
				LocationManager locManager = (LocationManager) getActivity()
						.getSystemService(Context.LOCATION_SERVICE);
				Criteria criteria = new Criteria();
				provider = locManager.getBestProvider(criteria, false);
				Location lastKnownLoc = null;

				lastKnownLoc = locManager
						.getLastKnownLocation(LocationManager.GPS_PROVIDER);
				arrNearby = new ArrayList<Place>();
				arrNearby = nearbyBO.listNearbyPlace(
						lastKnownLoc.getLatitude(),
						lastKnownLoc.getLongitude(), 1000, getKeyword(),
						getFilter(), getSorter());
				// compare to radius, remove outer points
				if (arrNearby.size() != 0) {
					for (int i = 0; i < arrNearby.size(); i++) {
						Location tempLocation = new Location("TempLocation "
								+ i);
						tempLocation.setLatitude(arrNearby.get(i).getGeo()
								.getLatitude());
						tempLocation.setLongitude(arrNearby.get(i).getGeo()
								.getLongitude());

						double distance = tempLocation.distanceTo(lastKnownLoc);
						if (distance > 1000) {
							arrNearby.remove(i);
						}
					}
				}

				nearbyAdapter = new ListPlaceAdapter(getActivity(),
						R.layout.adapter_list_place, arrNearby);

				// set listview adapter and create event for items click
				listNearby.setAdapter(nearbyAdapter);

				if (arrNearby.size() == 0 || arrNearby == null) {
					AlertDialog.Builder alertDialog = new AlertDialog.Builder(
							getActivity());
					alertDialog.setTitle("Nearby Places");
					alertDialog.setMessage("Sorry! No nearby place detected");
					alertDialog.setNegativeButton("OK", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.cancel();
						}
					});
				}

			} catch (NullPointerException e) {
				Log.e("Nearby Fragment", e.toString() + "");
			}
			// Toast.makeText(ProxAlertActivity.this,
			// "Distance from Point:" + distance, Toast.LENGTH_LONG)
			// .show();
		}

		public void onStatusChanged(String s, int i, Bundle b) {
		}

		public void onProviderDisabled(String s) {
			locationSetting.showSettingsAlert();
		}

		public void onProviderEnabled(String s) {
		}
	}
}
